//
//  MNDAutoTenderViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/13.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDAutoTenderViewController.h"
#import "MNDAutoTenderModel.h"
#import "MNDAutoTenderAlertViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDUserModel.h"
#import "MNDWebViewController.h"
#import "TTTAttributedLabel.h"
#import "MNDRiskAssessWebViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenTermsAuthViewController.h"

typedef NS_ENUM(NSInteger,TextFieldType) {
    TextFieldTypeLeastYearApr = 101,
    TextFieldTypeMostYearApr,
    TextFieldTypeLeastMonth,
    TextFieldTypeMostMonth

};
@interface MNDAutoTenderViewController ()<UITextFieldDelegate, TTTAttributedLabelDelegate>
//用户存管状态
@property (strong, nonatomic) MNDAutoTenderModel *autoTenderModel;
//自动投标排名
@property (weak, nonatomic) IBOutlet UILabel *myRankLabel;
//预计自动投标总人数
@property (weak, nonatomic) IBOutlet UILabel *autoTenderTotalLabel;
//最少年利率
@property (weak, nonatomic) IBOutlet UITextField *leastYearAprTextField;
//最大年利率
@property (weak, nonatomic) IBOutlet UITextField *mostYearAprTextField;
//最少月份
@property (weak, nonatomic) IBOutlet UITextField *leastMonthTextField;
//最大月份
@property (weak, nonatomic) IBOutlet UITextField *mostMonthTextField;
//单笔最小投资金额
@property (weak, nonatomic) IBOutlet UITextField *leastInvestMoneyTextField;

//保存自动投标设置的数据
@property (weak, nonatomic) IBOutlet UIButton *saveAutoTenderDataBtn;
@property (weak, nonatomic) IBOutlet UISwitch *openOrCloseAutoTenderSwitch;
@property (weak, nonatomic) IBOutlet UIView *autoTenderSetView;

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *agreementLabel1;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *agreementLabel2;

@property(nonatomic, strong) MNDUserModel *userModel;

@property (nonatomic, copy) NSString *userPhone;

@end

@implementation MNDAutoTenderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialBarButtonItems];
    
    [self loadData];
    [self setupUI];
    
    [self addAgreementLabelAttribute:self.agreementLabel1];
    [self addAgreementLabelAttribute:self.agreementLabel2];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [self loadUserInfo];
    
    [self loadUserPhoneToDeposit:nil];
}

- (void)addAgreementLabelAttribute:(TTTAttributedLabel *)label {
    //设置高亮颜色
    label.highlightedTextColor = kColorDarkOrange;
    //检测类型
    label.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    label.delegate = self;
    //不显示下划线
    label.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"开启自动投标代表您已阅读并同意《自动投标授权协议》";
    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange = [[mutableAttributedString string] rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorDarkOrange} range:linkRange];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange = [text rangeOfString:@"《自动投标授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url = [NSURL URLWithString:kAutoTenderAccord];
    [label addLinkToURL:url withRange:linkRange];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    webVC.title = @"自动投标授权协议";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}

#pragma mark -加载数据
- (void)loadData {
    
    /*! 自动投标排名获取 */
    __weak typeof(self) weakSelf = self;
    
    [APIManager sendRequestWithPath:API_AUTO_TENDER_RANKING parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakSelf.autoTenderModel = [MNDAutoTenderModel mj_objectWithKeyValues:responseModel.data];
            weakSelf.myRankLabel.text = weakSelf.autoTenderModel.auto_tender_rank;
            weakSelf.autoTenderTotalLabel.text = weakSelf.autoTenderModel.forecast_tender_ranking;
            weakSelf.leastYearAprTextField.text = weakSelf.autoTenderModel.borrow_least_year_apr;
            weakSelf.mostYearAprTextField.text = weakSelf.autoTenderModel.borrow_most_year_apr;
            weakSelf.leastMonthTextField.text = weakSelf.autoTenderModel.borrow_least_deadline;
            weakSelf.mostMonthTextField.text = weakSelf.autoTenderModel.borrow_most_deadline;
            weakSelf.leastInvestMoneyTextField.text = weakSelf.autoTenderModel.borrow_money;
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserInfo {
    [self.view beginLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParam];
    
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            MNDUserModel *user = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            weakSelf.userModel = user;
            weakSelf.autoTenderStatus = user.userIsaddAutotender;
            if ([weakSelf.autoTenderStatus isEqualToString:@"-1"]) {//未开启
                weakSelf.openOrCloseAutoTenderSwitch.on = NO;
                weakSelf.autoTenderSetView.hidden = YES;
                weakSelf.agreementLabel2.hidden = YES;
                weakSelf.agreementLabel1.hidden = NO;
            }else {
                weakSelf.openOrCloseAutoTenderSwitch.on = YES;
                weakSelf.autoTenderSetView.hidden = NO;
                weakSelf.agreementLabel2.hidden = NO;
                weakSelf.agreementLabel1.hidden = YES;
            }
            [weakSelf.view endLoading];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [weakSelf.view endLoading];
        }
    } onFailure:^(NSError *error) {
        NSInteger errorType = [weakSelf.view blankPageTypeWithError:error];
        [weakSelf.view configBlankPage:errorType hasData:NO reloadButtonBlock:^(id sender) {
            [weakSelf loadUserInfo];
        }];
    }];
}

- (void)configContents {
 
}

#pragma mark -搭建界面
- (void)setupUI {
    //开关状态
    if ([self.autoTenderStatus isEqualToString:@"-1"]) {//未开启
        self.openOrCloseAutoTenderSwitch.on = NO;
        self.autoTenderSetView.hidden = YES;
    }else {
        self.openOrCloseAutoTenderSwitch.on = YES;
        self.autoTenderSetView.hidden = NO;
    }
    self.leastYearAprTextField.clearsOnBeginEditing = YES;
    self.mostYearAprTextField.clearsOnBeginEditing = YES;
    self.leastMonthTextField.clearsOnBeginEditing = YES;
    self.mostMonthTextField.clearsOnBeginEditing = YES;
    //切圆角
    self.saveAutoTenderDataBtn.layer.cornerRadius = 4;
    self.saveAutoTenderDataBtn.clipsToBounds = YES;
    
    [self setTextFieldContent];
}

//限制textfield输入的内容
- (void)setTextFieldContent {
    //最小年利率内容限制
    [[self.leastYearAprTextField rac_textSignal]subscribeNext:^(id x) {
        float texNum = self.leastYearAprTextField.text.floatValue;
        if (texNum < 0) {
            self.leastYearAprTextField.text = @"1.00";
        }else if (texNum > 24){
        self.leastYearAprTextField.text = @"24.00";
        } else {
        
        }
    }];
    //最大年利率内容限制
    [[self.mostYearAprTextField rac_textSignal]subscribeNext:^(id x) {
        float texNum = self.mostYearAprTextField.text.floatValue;
        if (texNum < 0) {
            self.mostYearAprTextField.text = @"1.00";
        }else if (texNum > 24){
            self.mostYearAprTextField.text = @"24.00";
        } else {
            
        }
    }];
    
    //最小月期限内容限制
    [[self.leastMonthTextField rac_textSignal]subscribeNext:^(id x) {
        float texNum = self.leastMonthTextField.text.floatValue;
        if (texNum < 0) {
            self.leastMonthTextField.text = @"1";
        }else if (texNum > 12){
            self.leastMonthTextField.text = @"12";
        } else {
            
        }
    }];
    
    //最大月期限内容限制
    [[self.mostMonthTextField rac_textSignal]subscribeNext:^(id x) {
        float texNum = self.mostMonthTextField.text.floatValue;
        if (texNum < 0) {
            self.mostMonthTextField.text = @"1";
        }else if (texNum > 12){
            self.mostMonthTextField.text = @"12";
        } else {
            
        }
    }];
    
    //最小投资金额内容限制
    [[self.leastInvestMoneyTextField rac_textSignal]subscribeNext:^(id x) {
        float texNum = self.leastInvestMoneyTextField.text.floatValue;
        if(texNum > 1000000) {
        self.leastInvestMoneyTextField.text = @"";
        }
    }];

}

- (void)initialBarButtonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *itemImage = [UIImage imageNamed:@"notice_help_icon"];
    UIBarButtonItem *helpItem = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                                 style: UIBarButtonItemStylePlain
                                                                target: self
                                                                action: @selector(clickAutoTenderExplainButton:)];
    helpItem.tintColor = kColorOrange;
    
//    self.leftBarTintColor = kColorOrange;
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = helpItem;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, helpItem];
    }
}

#pragma mark -点击自动投标说明按钮
- (IBAction)clickAutoTenderExplainButton:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDAutoTenderAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDAutoTenderAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    //    __weak typeof(self) weakSelf = self;
    [alertVC.closeButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark -自动投标设置

- (IBAction)clickOpenOrCloseAutoTender:(UISwitch *)sender {
    
    [self.autoTenderSetView setHidden:!sender.isOn];
    [self.agreementLabel2 setHidden:!sender.isOn];
    [self.agreementLabel1 setHidden:sender.isOn];
    
    if (!sender.on) {
        //关闭自动投标
        [APIManager sendRequestWithPath:API_AUTO_TENDER_CLOSE parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            if (responseModel.status == ResponseSuccess) {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
            } else {
                [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            }
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD showHudNetworkError:error];
        }];
    }
}

//保存自动投标设置
- (IBAction)saveAutoTenderSetButton:(UIButton *)sender {
    
    [SVProgressHUD showWithStatus:@"请稍后"];
    
    NSDictionary *dict = @{
                           @"borrow_least_year_apr":self.leastYearAprTextField.text,
                           @"borrow_most_year_apr":self.mostYearAprTextField.text,
                           @"borrow_least_deadline":self.leastMonthTextField.text,
                           @"borrow_most_deadline":self.mostMonthTextField.text,
                           @"borrow_money":self.leastInvestMoneyTextField.text
                           };
    NSDictionary *params = [MNDSign signedParamWithDict: dict];
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_AUTO_TENDER_AUTO_SET parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        [SVProgressHUD dismiss];
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
        } else {
            NSDictionary *dic = responseModel.msg;
            if ([dic.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                    [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                    [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                    ) {
                    [weakself showOpenDepositAlert:responseModel];
                }else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }
                
            } else {
                [NetworkProgressHUD showHudMsg:dic[@"error"]];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
         [SVProgressHUD dismiss];
    }];
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)showOpenDepositAlert:(ResponseModel *)response {
    
    NSString *signStr = response.msg[@"sign"];
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    //风险评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlert];
        return;
    }
    
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
    
    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.tabBarController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        
        [weakself toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger fromIndex = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = fromIndex;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    //授权三合一
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] || [signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender] || [signStr isEqualToString:kSignAutoTransfer]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = fromIndex;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
    }
    
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
//        
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = fromIndex;
//        
//        [self.navigationController pushViewController:paymentVC animated:YES];
//        
//        return;
//    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//        
//        if (self.userPhone.length > 0) {
//            MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//            tenderVC.isResign = [signStr isEqualToString:kExpiredAutotender];
//            tenderVC.fromNaviIndex = fromIndex;
//            tenderVC.phoneNumber = self.userPhone;
//                
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhoneToDeposit:signStr];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//        
//        if (self.userPhone.length > 0) {
//            MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//            transferVC.fromNaviIndex = fromIndex;
//            transferVC.phoneNumber = self.userPhone;
//                
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhoneToDeposit:signStr];
//        }
//        return;
//    }
}

/**
 获取存管手机号
 */
- (void)loadUserPhoneToDeposit:(NSString *)depositStr {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userPhone = responseModel.data;
            NSInteger fromIndex = [weakself.navigationController.viewControllers indexOfObject:weakself];
            if ([depositStr isEqualToString:kSignAutoTender] || [depositStr isEqualToString:kExpiredAutotender]) {
                MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
                tenderVC.isResign = [depositStr isEqualToString:kExpiredAutotender];
                tenderVC.fromNaviIndex = fromIndex;
                tenderVC.phoneNumber = weakself.userPhone;
                
                [weakself.navigationController pushViewController:tenderVC animated:YES];
            }
            
            if ([depositStr isEqualToString:kSignAutoTransfer]) {
                MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
                transferVC.fromNaviIndex = fromIndex;
                transferVC.phoneNumber = weakself.userPhone;
                
                [weakself.navigationController pushViewController:transferVC animated:YES];
            }
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -UITextFieldDelegate
//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 
//    if (![string isEqualToString:@""]) {
//        NSLog(@"%@",textField.text);
//    }
    if (textField.tag == TextFieldTypeLeastYearApr || textField.tag == TextFieldTypeMostYearApr || [textField isEqual:_leastInvestMoneyTextField]) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
    
    }else {
         return [self validateNumber:string];
      }

    return YES;
}



- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == TextFieldTypeLeastYearApr || textField.tag == TextFieldTypeMostYearApr) {
        if (textField.text.floatValue >24) {
            textField.text = @"24.00";
        }
        if (textField.text.floatValue < 1) {
            textField.text = @"1.00";
        }
       
    }else if ([textField isEqual:_leastInvestMoneyTextField]) {
        if (_leastInvestMoneyTextField.text.doubleValue > 1000000) {
            _leastInvestMoneyTextField.text = @"不限";
        }
    }else {
        if (textField.text.floatValue >12) {
            textField.text = @"12";
        }
        if (textField.text.floatValue < 1) {
            textField.text = @"1";
        }
    }
    
}


- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showRiskAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.hidesBottomBarWhenPushed = YES;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
